package com.cy.store.Controller;

import com.cy.store.Controller.ex.*;
import com.cy.store.Entity.User;
import com.cy.store.Service.Ex.*;
import com.cy.store.Service.IUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cy.store.util.JsonResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//@Controller
@RestController//@Controller+@ResponseBody
@RequestMapping("/users")
public class UserController extends BaseController{

    @Autowired
    private IUserService userService;


    /**
     * 注册
     * @param user
     * @return
     * @throws UsernameDuplicatedException
     * @throws InsertException
     */
    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user) throws UsernameDuplicatedException, InsertException {
        userService.reg(user);
        return new JsonResult<>(OK);

    }


    /**
     * 登录
     * @param username
     * @param password
     * @param session
     * @return
     * @throws UserNotFoundException
     * @throws InsertException
     * @throws PasswordNotMatchException
     * @throws UsernameDuplicatedException
     */
    @RequestMapping("/login")
    public JsonResult<User> login(String username, String password
            , HttpSession session) throws UserNotFoundException, InsertException
            , PasswordNotMatchException, UsernameDuplicatedException {
        User data=userService.login(username,password);

        //向session对象中完成数据的绑定(全局)
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());

//        //获取session中绑定的数据
//        System.out.println(getuidFromSession(session));
//        System.out.println(getusernameFromSession(session));

        return new JsonResult<>(OK,data);


    }


    /**
     * 修改密码（更新数据）
     */
    @RequestMapping("/changeUsersPassword")
    public JsonResult<Void> changePassword(String oldPassword, String newPassword
    ,HttpSession session) throws UserNotFoundException, InsertException, PasswordNotMatchException, UpdateException {
        Integer uid=getuidFromSession(session);
        String username=getusernameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    @RequestMapping("/getByUid")
    public JsonResult<User> getByUid( HttpSession session) throws UserNotFoundException {
        User data=userService.getByUid(getuidFromSession(session));
        return new JsonResult<>(OK,data);
    }

    @RequestMapping("/changeInfo")
    public JsonResult<Void> changeInfo(User user,HttpSession session) throws UserNotFoundException, UpdateException {
        //user对象中有四部分数据：username、phone、email、gender
        Integer uid=getuidFromSession(session);
        String username=getusernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

    //设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE=10*1024*1024;

    //限制上传文件的类型
    public static final List<String> AVATAR_TYPE=new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/jpg");
        AVATAR_TYPE.add("image/gif");
        AVATAR_TYPE.add("image/bmg");

    }


    /**
     * MultipartFile是springMVC提供的接口，可以接收任何类型的文件，而springboot整合了springMVC。
     * RequestParam名称不一致的时候对应用的
     * @param session
     * @param file
     * @return
     */
    @RequestMapping("/change_avatar")
    public JsonResult<String> changeAvatar(
            HttpSession session,
            @RequestParam("file") MultipartFile file) throws UserNotFoundException, UpdateException {
        if(file.isEmpty()){
            throw new FileEmptyException("文件不能为空");
        }
        //在原有大小不限的情况下才有作用，springmvc默认大小1MB
        if(file.getSize()>AVATAR_MAX_SIZE){
            throw new FileSizeException("文件大小不能超过10MB");
        }
        String contentType=file.getContentType();
        if(!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("文件类型不支持");
        }
        //上传图片的绝对储存路径
//        String parent=session.getServletContext().getRealPath("/upload");
        String parent="D:/.IdeaProject/self-developed/store/upload";
        System.out.println(parent);
        //File对象指向这个路径
        File dir=new File(parent);
        if(!dir.exists()){
            //创建当前目录
            dir.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename:"+originalFilename);
        int index=originalFilename.lastIndexOf(".");
        //截取文件的后缀
        String suffix=originalFilename.substring(index);
        //生成随机大写字母的文件名并与后缀拼接作为最终的文件名
        String filename= UUID.randomUUID().toString().toUpperCase()+suffix;
        //创建一个空文件夹
        File dest=new File(dir,filename);
        //将参数file中的数据写入到空文件夹中
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        }
        //开始更换头像

        Integer uid = getuidFromSession(session);
        String username = getusernameFromSession(session);
        String avatar="/upload/"+filename;
        userService.changeAvatar(uid,avatar,username);
        //返回用户头像的路径给前端页面，用于前端展示使用
        return new JsonResult<>(OK,avatar);
    }
}
